/**
* Copyright (c) 2025 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
#include "data_utils.h"
#include <cstdint>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include "acl/acl.h"
#include "kernel_operator.h"
#include "kernel_operator_list_tensor_intf.h"

constexpr int32_t BUFFER_NUM = 1;

struct BroadcastCustomTilingData
{
    uint32_t totalLength;
    uint32_t tileNum;
    uint32_t tmpSize;
    uint32_t dim;
    uint32_t axis;
    uint32_t num;
    uint32_t bLength;
};

class KernelBroadcastCustom {
public:
    __aicore__ inline KernelBroadcastCustom() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, uint32_t totalLength, uint32_t tileNum, uint32_t tmpSize,
                                uint32_t dim, uint32_t axis, uint32_t num, uint32_t bLength)
    {
        this->blockLength = totalLength / AscendC::GetBlockNum();
        this->tileNum = tileNum;
        this->tileLength = this->blockLength / tileNum / BUFFER_NUM;
        this->dim = dim;
        this->tmpSize = tmpSize;
        this->axis = axis;
        this->num = num;
        this->bLength = bLength;
        if (this->dim == 1) {
            this->tileLength2 = num;
        } else {
            this->tileLength2 = this->tileLength * num;
        }

        xGm.SetGlobalBuffer((__gm__ float *)x + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        yGm.SetGlobalBuffer((__gm__ float *)y + this->tileLength2 * AscendC::GetBlockIdx(), this->blockLength);

        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(outQueueY, BUFFER_NUM, this->tileLength2 * sizeof(float));
        if (this->tmpSize != 0) {
            pipe.InitBuffer(tmpQueue, this->tmpSize);
        }
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        AscendC::DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
        inQueueX.EnQue(xLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<float> yLocal = outQueueY.AllocTensor<float>();

        if (this->tmpSize == 0) {
            if (this->dim == 1) {
                const uint32_t srcShape[] = {1};
                const uint32_t dstShape[] = {this->num};
                AscendC::BroadCast<float, 1, 0>(yLocal, xLocal, dstShape, srcShape);
            } else {
                const uint32_t srcShape[] = {this->bLength, this->tileLength / this->bLength};
                if (this->axis == 0) {
                    const uint32_t dstShape[] = {this->bLength * this->num, this->tileLength / this->bLength};
                    AscendC::BroadCast<float, 2, 0>(yLocal, xLocal, dstShape, srcShape);
                } else {
                    const uint32_t dstShape[] = {this->bLength, this->tileLength / this->bLength * this->num};
                    AscendC::BroadCast<float, 2, 1>(yLocal, xLocal, dstShape, srcShape);
                }
            }
        } else {
            AscendC::LocalTensor<uint8_t> tmpTensor = tmpQueue.Get<uint8_t>();
            if (this->dim == 1) {
                const uint32_t srcShape[] = {1};
                const uint32_t dstShape[] = {this->num};
                AscendC::BroadCast<float, 1, 0>(yLocal, xLocal, dstShape, srcShape, tmpTensor);
            } else {
                const uint32_t srcShape[] = {this->bLength, this->tileLength / this->bLength};
                if (this->axis == 0) {
                    const uint32_t dstShape[] = {this->bLength * this->num, this->tileLength / this->bLength};
                    AscendC::BroadCast<float, 2, 0>(yLocal, xLocal, dstShape, srcShape, tmpTensor);
                } else {
                    const uint32_t dstShape[] = {this->bLength, this->tileLength / this->bLength * this->num};
                    AscendC::BroadCast<float, 2, 1>(yLocal, xLocal, dstShape, srcShape, tmpTensor);
                }
            }
            tmpQueue.FreeTensor(tmpTensor);
        }

        outQueueY.EnQue<float>(yLocal);
        inQueueX.FreeTensor(xLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> yLocal = outQueueY.DeQue<float>();
        AscendC::DataCopy(yGm[progress * this->tileLength2], yLocal, this->tileLength2);
        outQueueY.FreeTensor(yLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueY;
    AscendC::TBuf<AscendC::TPosition::VECCALC> tmpQueue;
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> yGm;
    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
    uint32_t tileLength2;
    uint32_t dim;
    uint32_t tmpSize;
    uint32_t axis;
    uint32_t num;
    uint32_t bLength;
};

__global__ __aicore__ void broadcast_custom(GM_ADDR x, GM_ADDR y, BroadcastCustomTilingData tiling)
{
    KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY);

    KernelBroadcastCustom op;
    op.Init(x, y, tiling.totalLength, tiling.tileNum, tiling.tmpSize, tiling.dim, tiling.axis,
            tiling.num, tiling.bLength);
    op.Process();
}

int32_t main(int32_t argc, char *argv[])
{
    constexpr uint32_t blockDim = 8;
    size_t inputSize = 4096 * 1 * sizeof(float);
    size_t outputSize = 4096 * 3 * sizeof(float);
    int32_t deviceId = 0;
    aclrtStream stream = nullptr;
    BroadcastCustomTilingData tiling = {4096, 1, 0, 2, 1, 3, 1};

    aclInit(nullptr);
    aclrtSetDevice(deviceId);
    aclrtCreateStream(&stream);

    uint8_t *xHost;
    uint8_t *xDevice;
    aclrtMallocHost((void **)(&xHost), inputSize);
    aclrtMalloc((void **)&xDevice, inputSize, ACL_MEM_MALLOC_HUGE_FIRST);
    ReadFile("./input/input_x.bin", inputSize, xHost, inputSize);
    aclrtMemcpy(xDevice, inputSize, xHost, inputSize, ACL_MEMCPY_HOST_TO_DEVICE);

    uint8_t *zHost;
    uint8_t *zDevice;
    aclrtMallocHost((void **)(&zHost), outputSize);
    aclrtMalloc((void **)&zDevice, outputSize, ACL_MEM_MALLOC_HUGE_FIRST);

    broadcast_custom<<<blockDim, nullptr, stream>>>(xDevice, zDevice, tiling);
    aclrtSynchronizeStream(stream);

    aclrtMemcpy(zHost, outputSize, zDevice, outputSize, ACL_MEMCPY_DEVICE_TO_HOST);

    WriteFile("./output/output.bin", zHost, outputSize);

    aclrtFree(xDevice);
    aclrtFree(zDevice);
    aclrtFreeHost(xHost);
    aclrtFreeHost(zHost);

    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}